package com.lld.httpdemo.controller;

import com.lld.httpdemo.utils.MD5Util;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 调用http请求controller
 *
 * @author liulindong
 * @since 2022/7/25 10:22
 */
@RestController
@RequestMapping(value = "/http_test")
public class HttpClientController {

    /**
     * 问卷网注册用户接口
     */
    private static final String WJ_REGISTER_USER = "https://open.wenjuan.com/openapi/v4/register?app_key={appKey}&timestamp={timestamp}&signature={signature}&outer_id={memberId}";

    private static final String APP_KEY = "wjOH1b7yQEp3xMr8nl";

    private static final String APP_SECRET = "372RH5ydVtEzYJTncWeXIfmDP8OQvFZk";


    /**
     * 问卷网注册用户
     * @return 返回的json结果
     */
    @GetMapping("/wj_register")
    public String register() {
        long timestamp = System.currentTimeMillis() / 1000;
        String memberId = "lkjlkjkljasdfhlkjsdf";
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("appKey", APP_KEY);
        queryParams.put("timestamp", timestamp);
        queryParams.put("memberId", memberId);
        queryParams.put("signature", MD5Util.encrypt(APP_KEY + memberId + timestamp + APP_SECRET));
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(WJ_REGISTER_USER, HttpMethod.GET, entity, String.class, queryParams);
        return response.getBody();
    }
}
